import Typewriter, { TypewriterClass } from 'typewriter-effect';
import React, { useCallback, useEffect, useRef } from 'react';

export type TextAutoPlayProps = {
  text?: string
}



function useTextAutoPlay(props: TextAutoPlayProps) {

  const writeRef = useRef<TypewriterClass>()

  const handleTypeInit = useCallback((typewriter: TypewriterClass) => {
    if (props.text) {
      typewriter.typeString(props.text)
        .start()
    }
    writeRef.current = typewriter
  }, [props.text])

  useEffect(() => {
    if (props.text && writeRef.current) {
      writeRef.current.deleteAll(0)
        .typeString(props.text).start()
    }
  }, [props.text])

  return {
    handleTypeInit
  }
}
export function TextAutoPlay(props: TextAutoPlayProps) {

  const { handleTypeInit } = useTextAutoPlay(props)
  return (
    <Typewriter
      onInit={handleTypeInit}
      options={{autoStart: false, delay: 20}}
    />
  )
}